package com.jzo2o.customer.controller.open;

import com.jzo2o.common.constants.CommonRedisConstants;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.Result;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.LoginForAgencyReqDTO;
import com.jzo2o.customer.model.dto.request.LoginForWorkReqDTO;
import com.jzo2o.customer.model.dto.request.SmsCodeSendReqDTO;
import com.jzo2o.customer.service.IServeProviderService;
import io.swagger.annotations.Api;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author wjh
 * @create 2024-04-22 12:17
 */
@Api(tags = "机构端注册认证")
@RestController("openServeProviderController")
@RequestMapping("/open/serve-provider")
public class ServeProviderController {
    
    @Resource
    private IServeProviderService serveProviderService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private PasswordEncoder passwordEncoder;
    
    
    @PostMapping("/institution/register")
    public Result register(@RequestBody LoginForAgencyReqDTO loginForAgencyReqDTO) {
        String redisKey = String.format(CommonRedisConstants.RedisKey.VERIFY_CODE, loginForAgencyReqDTO.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER.getType());
        if (Boolean.FALSE.equals(redisTemplate.hasKey(redisKey))) {
            throw new BadRequestException("验证码已过期");
        }
        if (!ObjectUtils.equals(redisTemplate.opsForValue().get(redisKey), loginForAgencyReqDTO.getVerifyCode())) {
            throw new BadRequestException("验证码错误");
        }
        if (StringUtils.isBlank(loginForAgencyReqDTO.getPassword())) {
            throw new BadRequestException("密码不能为空");
        }
        ServeProvider serveProvider = serveProviderService.add(loginForAgencyReqDTO.getPhone(), UserType.INSTITUTION, passwordEncoder.encode(loginForAgencyReqDTO.getPassword()));
        if (serveProvider == null) {
            throw new BadRequestException("注册失败");
        }
        redisTemplate.delete(redisKey);
        return Result.ok("注册成功");
    }
}
